<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item  :to="{ path: '/square' }">
                    <i class="el-icon-lx-file"></i> 数据广场
                </el-breadcrumb-item>
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 收藏文件详情
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-button type="success" size="medium" icon="el-icon-plus" @click="handleAnalysis">数据统计配置</el-button>

                <el-button type="primary" size="medium" icon="el-icon-plus" @click="createConfig">AI模型配置</el-button>

                <el-button type="primary" size="medium" @click="handleAnalysisByHand">重新分析</el-button>
            </div>

            <el-table :data="tableData"
                      border class="table"
                      ref="fieldTable"
                      header-cell-class-name="table-header"
                      @selection-change="handleSelectChange"
                      :row-style="tableRowStyle"
            >
                <el-table-column width="50" type="selection"></el-table-column>
                <el-table-column label="序号">
                    <template #default="scope"><span>{{ scope.$index + 1 }}</span></template>
                </el-table-column>
                <el-table-column label="字段名">
                    <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
                </el-table-column>
                <el-table-column label="取值类型">
                    <template #default="scope">{{ scope.row.dataType }}</template>
                </el-table-column>
                <el-table-column label="空值率">
                    <template #default="scope">{{ handleNullRate(scope.row.nullRate) }}</template>
                </el-table-column>
                <el-table-column label="众数">
                    <template #default="scope">{{ scope.row.majority }}</template>
                </el-table-column>
            </el-table>
            <div class="pagination">
                <el-pagination background layout="total, prev, pager, next" :current-page="query.pageIndex"
                               :page-size="query.pageSize" :total="pageTotal" @current-change="handlePageChange"></el-pagination>
            </div>
        </div>

        <el-dialog title="新建数据统计配置" v-model="analysisVisible" width="50%">
            <el-form label-position="left">
                <el-form-item label="配置名" required>
                    <el-input v-model="analysisConfName"></el-input>
                </el-form-item>
                <el-alert type="info"
                          show-icon style="line-height: 20px; margin-bottom: 20px">不同方法仅适用于特定特征字段。<br>
                    皮尔森相关系数需要2个int/double字段，散点图可以传入2个字段，其他的方法只需一个字段。<br>除了数据分布可以传入string字段，其他方法请传入int/double字段。</el-alert>
            </el-form>
            <el-table :data="selectData" border class="table" size="small" header-cell-class-name="table-header">
                <el-table-column label="已选字段名">
                    <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
                </el-table-column>
                <el-table-column label="字段类型">
                    <template #default="scope"><span>{{ scope.row.dataType }}</span></template>
                </el-table-column>
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="analysisVisible = false" size="medium">再想想</el-button>
                    <el-button type="primary" @click="createAnalysisConfig()" size="medium">确定</el-button>
                </span>
            </template>
        </el-dialog>

        <el-dialog title="新建AI模型配置" v-model="configCreate" width="50%">
            <el-form label-width="90px" label-position="left">
                <el-form-item label="配置名" required>
                    <el-input v-model="form.name"></el-input>
                </el-form-item>

                <el-form-item label="模型类别" required>
                    <el-select v-model="form.type" placeholder="学习类型" class="handle-select mr10">
                        <el-option key="1" label="监督学习" value="SUPERVISED_LEARNING"></el-option>
                        <el-option key="2" label="非监督学习" value="UNSUPERVISED_LEARNING"></el-option>
                    </el-select>
                    <el-alert type="info" description="您选择的最后一个字段为标签字段" v-if="form.type === 'SUPERVISED_LEARNING'"
                              show-icon style="height: 40px; margin-top: 10px"></el-alert>
                    <el-alert type="info" description="没有目标字段,适用于k-means模型" v-if="form.type === 'UNSUPERVISED_LEARNING'"
                              show-icon style="height: 40px; margin-top: 10px"></el-alert>
                </el-form-item>

                <el-table :data="selectData" border class="table" header-cell-class-name="table-header" size="small"
                          v-if="form.type !== 'SUPERVISED_LEARNING'">
                    <el-table-column label="已选字段名">
                        <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
                    </el-table-column>
                    <el-table-column label="字段类型">
                        <template #default="scope"><span>{{ scope.row.dataType }}</span></template>
                    </el-table-column>
                </el-table>

                <el-table :data="selectData" border class="table" header-cell-class-name="table-header" size="small"
                          :row-style="AITableRowStyle" v-if="form.type === 'SUPERVISED_LEARNING'">
                    <el-table-column label="已选字段名">
                        <template #default="scope"><span>{{ scope.row.fieldName }}</span></template>
                    </el-table-column>
                    <el-table-column label="字段类型">
                        <template #default="scope"><span>{{ scope.row.dataType }}</span></template>
                    </el-table-column>
                </el-table>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="configCreate = false" size="medium">再想想</el-button>
                    <el-button type="primary" @click="saveConfig" size="medium">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import {ref, reactive} from "vue";
    import { ElMessage, ElMessageBox } from "element-plus";
    import {getFileDescribe, getFileDetail} from "../../api/file";
    import {useRoute}from "vue-router";
    import {useRouter}from "vue-router";
    import {addConfig} from "../../api/config";
    import {addAnalysisConfig} from "../../api/analysisConfig";

    export default {
        name: "CollectFileDetail",
        //训练特征
        setup() {
            const router=useRouter();
            const query = reactive({
                address: "",
                name: "",
                pageIndex: 1,
                pageSize: 10,
            });
            let fileInfoId;
            let AnalysisMethodName=["数据分布","散点图","数据统计","偏度-峰度","皮尔森相关系数"];

            const tableData = ref([]);
            const selectData = ref([]);
            let analysisData=reactive([])
            const pageTotal = ref(0);

            // 获取表格数据
            const getData = () => {
                const route=useRoute()
                console.log(route.query)
                if(route.query.fileId!=null) {
                    const payload ={
                        fileInfoId: route.query.fileId,
                        userId: localStorage.getItem("ms_userId")
                    }
                    getFileDetail(payload).then(res => {
                        tableData.value = res.result.fileFields;
                        pageTotal.value = tableData.value.length
                        fileInfoId=route.query.fileId
                    })
                }
            };
            getData();

            // 查询操作
            const handleSearch = () => {
                query.pageIndex = 1;
                getData();
            };
            // 分页导航
            const handlePageChange = (val) => {
                query.pageIndex = val;
                getData();
            };

            // 表格编辑时弹窗和保存
            let analysisVisible = ref(false);
            let form = reactive({
                name: "",
                type: "",
                needLabel: "",
            });
            let analysisConfName = ref();

            const handleAnalysis = () => {
                if (selectData.value.length<1){
                    ElMessage.warning("请选择需要的字段！");
                    return ;
                }
                analysisVisible.value = true;
            };
            const createAnalysisConfig = () => {
                const payload={
                    fileInfoId:selectData.value[0].fileInfoId,
                    userId: localStorage.getItem("ms_userId"),
                    configName:analysisConfName.value,
                    chosenColumns:[],
                }
                if(payload.configName === undefined){
                    ElMessage.warning("请输入配置名！")
                    return
                }
                for(let i=0;i<selectData.value.length;i++){
                    payload.chosenColumns.push(selectData.value[i].fieldName);
                }
                console.log("p"+JSON.stringify(payload))
                addAnalysisConfig(payload).then(res=>{
                    console.log("r"+JSON.stringify(res))
                    if(res.msg === '成功') {
                        ElMessage.success(`已成功生成数据统计配置`);
                        analysisVisible.value = false;
                    }
                    else ElMessage.error(`生成数据统计配置失败:`+res.msg);
                })
            };

            let resultVisible= ref(false);
            let featureTip=ref(0);
            let labelTip = ref(0);

            const configCreate = ref(false);
            const createConfig =() => {
                if (selectData.value.length<=1){
                    ElMessage.warning("请选择至少两个字段！若为监督学习，最后选择的字段将作为标签");
                    return ;
                }
                configCreate.value = true;
            };
            const saveConfig=()=>{
                const payload={
                    fileInfoId:selectData.value[0].fileInfoId,
                    userId: localStorage.getItem("ms_userId"),
                    learningType:form.type,
                    configName:form.name,
                    features:[],
                    label: ''
                }
                if(payload.configName === "" || payload.learningType === "" ){
                    ElMessage.warning("请输入必要信息！")
                    return
                }
                if (form.type === 'UNSUPERVISED_LEARNING'){
                    for(let i=0;i<selectData.value.length;i++){
                        payload.features.push(selectData.value[i].fieldName);
                    }
                }
                else{
                    for(let i=0;i<selectData.value.length-1;i++){
                        payload.features.push(selectData.value[i].fieldName);
                    }
                    payload.label = selectData.value[selectData.value.length-1].fieldName
                }
                addConfig(payload).then(res=>{
                    console.log(res)
                    if(res.msg === '成功') {
                        ElMessage.success(`已成功生成AI模型配置`);
                        configCreate.value = false;
                    }
                    else ElMessage.error(`生成AI模型配置失败`+res.msg);
                })
            }

            let ids=ref([]);

            const handleSelectChange=val=>{
                selectData.value=val;
                ids = val.map(item => item.id);
                //console.log(ids)
            };

            const handleAnalysisByHand=()=>{
                ElMessage.warning(`重新分析文件中，请稍候`);
                const payload ={
                    fileInfoId: fileInfoId,
                    userId: localStorage.getItem("ms_userId")
                }
                getFileDescribe(payload)
                    .then(res=>{
                        ElMessage.success(`已成功重新分析文件`);
                        setTimeout(() => {
                            // 方法区
                            location.reload();
                        }, 2000);

                    })
            };

            const handleNullRate=(val)=>{
                return val + "%";
            };

            const AITableRowStyle=(row)=> {
                let rowFont = {};
                if (row.rowIndex === selectData.value.length - 1) {
                    rowFont.color = "red";
                    return rowFont;
                } else {
                    return '';
                }
            };

            const tableRowStyle=(row)=>{
                let arr = ids;
                let rowFont = {};
                if(row.row.id === arr[arr.length - 1]){
                    rowFont.color = "red";
                    return rowFont;
                }
            };

            return {
                query,
                AnalysisMethodName,
                tableData,
                pageTotal,
                analysisVisible,
                resultVisible,
                form,
                analysisConfName,
                configCreate,
                createConfig,
                saveConfig,
                selectData,
                analysisData,
                featureTip,
                labelTip,
                getData,
                createAnalysisConfig,
                handleSelectChange,
                handleSearch,
                handlePageChange,
                handleAnalysis,
                handleNullRate,
                handleAnalysisByHand,
                AITableRowStyle,

                ids,
                tableRowStyle
            };
        },
    };


</script>

<style scoped>
    .handle-box {
        margin-bottom: 20px;
    }

    .handle-select {
        width: 120px;
    }

    .handle-input {
        width: 300px;
        display: inline-block;
    }
    .table {
        width: 100%;
        font-size: 14px;
    }
    .red {
        color: skyblue;
    }
    .mr10 {
        margin-right: 10px;
    }
    .table-td-thumb {
        display: block;
        margin: auto;
        width: 40px;
        height: 40px;
    }

</style>
